package pl.uz.zgora.plan;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.ksoap2.SoapFault;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;

public class NewsViewActivity extends Activity {

	final private ArrayList<News> newsList = new ArrayList<News>();
	
	@Override
	public Object onRetainNonConfigurationInstance() {
	    return newsList;
	}

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.news_view);
	    
	    if(HelperMethodsManager.isOnline(this)) {
	    	final ListView listView = (ListView) findViewById(R.id.newslist);
	    	{
	    		/**
	    		 * OnClickListener wyświetlający w przeglądarce wybranego newsa
	    		 */
	    		listView.setOnItemClickListener(new OnItemClickListener() {

	    			public void onItemClick(AdapterView<?> parent, View view,
	    					int position, long id) {
	    				String url = newsList.get(position).getLink();
	    				if(url != null && !url.equals("")){
	    					url = "http://www.samorzad.uz.zgora.pl/" + url;
	    					final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
	    					startActivity(browserIntent);
	    				}
	    			}
	    		});
	    	}

	    	@SuppressWarnings("unchecked")
	    	final ArrayList<News> lastNonConfigurationInstance = (ArrayList<News>) getLastNonConfigurationInstance();
	    	if(lastNonConfigurationInstance != null) {
	    		newsList.clear();
	    		newsList.addAll(lastNonConfigurationInstance);
	    	}

	    	if(newsList.size() > 0) {
	    		final LinearLayout layout = (LinearLayout) findViewById(R.id.layoutDownloadProgress);
	    		layout.setVisibility(View.GONE);
	    		showNews(listView);
	    	} else {
	    		final SOAPManager soapManager = new SOAPManager(this);
	    		Thread viewNews = new Thread(new Runnable() {

	    			public void run() {

	    				if(newsList.size() == 0) {

	    					try {
	    						soapManager.downloadNews(newsList);
	    						manageNewsUI(newsList);

	    						if(newsList.size() > 0) {
	    							showNews(listView);
	    						} else {
	    							HelperMethodsManager.manageException("onCreate()", "Błąd podczas pobierania danych", NewsViewActivity.this);
	    						}
	    					} catch (SoapFault e) {
	    						HelperMethodsManager.manageException("onCreate()", e.getLocalizedMessage(), NewsViewActivity.this);
	    					} catch (UnsupportedEncodingException e) {
	    						HelperMethodsManager.manageException("onCreate()", e.getLocalizedMessage(), NewsViewActivity.this);
	    					} catch (IOException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					} catch (XmlPullParserException e) {
	    						// TODO Auto-generated catch block
	    						e.printStackTrace();
	    					}
	    				}
	    			}
	    		});
	    		viewNews.start();
	    	}
	    } else {
	    	final LinearLayout layoutDownloadProgress = (LinearLayout) findViewById(R.id.layoutDownloadProgress);
	    	layoutDownloadProgress.setVisibility(View.GONE);
	    	Dialog errorDialog = HelperMethodsManager.getConnectionErrorDialog(this, this);
	    	errorDialog.show();
	    }
	}
	
	private void manageNewsUI(final ArrayList<News> newsList) {
		final LinearLayout layoutDownloadProgress = (LinearLayout) findViewById(R.id.layoutDownloadProgress);
		
		layoutDownloadProgress.post(new Runnable() {
			
			public void run() {
				layoutDownloadProgress.setVisibility(LinearLayout.GONE);
			}
		});
	}
	
	private void showNews(final ListView listView) {
		String[] values = new String[newsList.size()];
		for(int i = 0; i < newsList.size(); i++) {
			values[i] = newsList.get(i).getTresc();
		}
		final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_2, android.R.id.text1, values);
		
		listView.post(new Runnable() {

			public void run() {
				listView.setAdapter(adapter);
			}
		});
	}
	
	
}
